package com.config;

import com.annocation.Value;
import com.entity.DataBaseAdmin;
import lombok.Data;
import lombok.Getter;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Properties;

import static com.util.Constant.APPLICTION_FILE;


@Data
public class DBConfig {
    private static final String APPLICATION_NAME=APPLICTION_FILE;

    @Getter
    private static DBConfig instance = new DBConfig();//一个单例

    @Value(value = "datasource.driverclassName")
    private String driverclassName;

    @Value(value = "datasource.jdbcUrl")
    private String jdbcUrl;

    @Value(value = "datasource.username")
    private String username;

    @Value(value = "datasource.password")
    private String password;

    private  DBConfig(){
        Field[] declaredField = DBConfig.class.getDeclaredFields();
        Properties properties = LoadProperties();
        Arrays.stream(declaredField).filter(f -> f.isAnnotationPresent(Value.class)).forEach(f ->{
            String property = properties.getProperty(f.getAnnotation(Value.class).value());
            try {
                f.set(this,property);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
    }

    private static Properties LoadProperties(){
        Properties properties = new Properties();
        try(InputStream in = DataBaseAdmin.class.getClassLoader().getResourceAsStream(APPLICATION_NAME);
        ){
            properties.load(in);
            return properties;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
